#!/usr/bin/env python
# -*- coding:utf-8 -*-
'''数据转换助手

历史:
    2018-11-03 姚彧 转换器(进行字符串到数组之间的相互转换)
    2018-11-05 ... text_table_to_str_array 加入分隔符
    2018-11-27 ... array_to_text_table 加入分隔符
'''


__all__ = ['Convertor']


import numpy as np


class Convertor(object):
    @staticmethod
    def text_table_to_str_array(text:str, func = None, sep = None):
        '''数值表格转数组'''
        assert isinstance(text, str)
        if not callable(func):
            func = lambda x: x
        rows = []
        for row in text.strip().split('\n'):
            rows.append([func(i.strip()) for i in row.split(sep)])
        if rows:
            n = len(rows[0])
            for i in range(1, len(rows)):
                assert len(rows[i]) == n, (n, i, rows)
        return rows

    @staticmethod
    def text_table_to_array(text:str, sep = None) -> np.ndarray:
        '''数值表格转数组'''
        points = Convertor.text_table_to_str_array(text, float, sep)
        return np.array(points)

    @staticmethod
    def array_to_text_table(values:np.ndarray, ndigits = 5, sep = '\t', newline = '\n') -> str:
        assert isinstance(ndigits, int) and  ndigits >= 0, ndigits
        values = np.asarray(values)
        assert isinstance(values, np.ndarray)
        values = np.round(values, ndigits).tolist()
        return newline.join([sep.join([str(j) for j in i]) for i in values])